package com.byxy.shop.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.byxy.shop.service.UserService;
import com.byxy.shop.entity.User;

/**
 * @author 廖善椅
 * @ClassName UserController
 * @Description 用户控制类
 * @date 2020年5月17日
 */

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	/** 登录 */
	@GetMapping("login")
	public String lonin() {
		return "mall/login";
	}

	@PostMapping("login")
	@ResponseBody
	public Map<String, String> doLogin(@RequestParam Map<String, String> data, HttpServletRequest req) {
		Map<String, String> result = new HashMap<>();
		String loginName = data.get("loginName");
		String password = data.get("password");
		User user = userService.login(loginName, password);
		if (user.getLoginName() != null) {
			req.getSession().setAttribute("newBeeMallUser", user);
			result.put("resultCode", "200");
		} else {
			result.put("message", "用户名或密码错误");
		}
		return result;
	}

	/** 退出登录 */
	@GetMapping("logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:index";
	}

	/** 注册 */
	@GetMapping("register")
	public String register() {
		return "mall/register";
	}

	@PostMapping("register")
	@ResponseBody
	public Map<String, String> doRegister(String loginName, String password, String verifyCode) {
		Map<String, String> result = new HashMap<>();
		User user = new User();
		user.setLoginName(loginName);
		user.setPasswordMd5(password);
		user.setNickName("");
		user.setIntroduceSign("");
		user.setCreateTime(new Date());
		user.setIsDeleted(0);
		user.setAddress("");
		user.setLockedFlag(0);
		User u = userService.save(user);
		if (u == null) {
			result.put("resultCode", "201");
			result.put("message", "用户名已经存在");
		} else {
			result.put("resultCode", "200");
		}
		return result;
	}
	
	/** 个人中心页 */
	@GetMapping("personal")
	public String personal() {
		return "mall/personal";
	}
	
	/** 修改个人信息 */
	@PostMapping("/personal/updateInfo")
	@ResponseBody
	public Map<String,String> updateInfo(@RequestBody User user, HttpServletRequest req){
		Map<String, String> result = new HashMap<>();
		int res = userService.updateUserInfo(user);
		if (res < 1) {
			result.put("resultCode", "201");
			result.put("message", "修改失败，稍后重试！");
		} else {
			User u = userService.getById(user.getUserId());
			req.getSession().setAttribute("newBeeMallUser", u);
			result.put("resultCode", "200");
		}
		return result;
	}
}
